package com.controller.broker;

import com.dao.Flight;
import com.util.Printer;
import com.util.Transformer;
import corba.airlineServer.Server;
import corba.airlineServer.ServerHelper;
import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Phillip on 2014/4/22.
 */
public class BrokerCORBAClient {

    private Server server;

    public BrokerCORBAClient() {
        ORB orb = ORB.init(new String[0], null);
        try {
            org.omg.CORBA.Object objectRef = orb.resolve_initial_references("NameService");
            NamingContext namingContext = NamingContextHelper.narrow(objectRef);
            NameComponent nameComponent = new NameComponent("corba.airlineServer.Server", "");
            NameComponent[] path = {nameComponent};
            objectRef = namingContext.resolve(path);
            server = ServerHelper.narrow(objectRef);

        } catch (InvalidName invalidName) {
            invalidName.printStackTrace();
        } catch (org.omg.CosNaming.NamingContextPackage.InvalidName invalidName) {
            invalidName.printStackTrace();
        } catch (CannotProceed cannotProceed) {
            cannotProceed.printStackTrace();
        } catch (NotFound notFound) {
            notFound.printStackTrace();
        }
    }

    public static void main(String[] args) {

    }

    public List<Flight> queryFlights(String deptString, String destString, String deptDateString, String returnDateString) {
        corba.airlineServer.Flight[] flightList = server.queryFlights2(deptString, destString, deptDateString, returnDateString);
        return Transformer.c2d(flightList);
    }

    public List<String> queryCity() {
        List<String> cityList = new ArrayList<>();
        String[] cities = server.queryCity2();
        Printer.p(cities.length);
        for (int i = 0; i < cities.length; i++) {
            cityList.add(cities[i]);
        }
        return cityList;
    }

    public String queryRates(String flightString, String classString) {

        return server.queryRates2(flightString, classString);
    }

    public String queryAirline(String deptString, String dsctString) {
        return server.queryAirline2(deptString, dsctString);
    }

    public String book(String flightNoString1, String deptString, String clasString1, String flightNoString2, String returnString, String classString2, String nameString, String creditString) {
        return server.book2(flightNoString1, deptString, clasString1, flightNoString2, returnString, classString2, nameString, creditString);
    }
}
